﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.IO;

[System.Serializable]
public struct DeploySpotInfo
{
	public Vector3 pos;
	public Quaternion rot;
	public Transform trans;
	public UICharToDeploy uiIcon;
	public int nLine;
}

public class ArmyDeploy : MonoBehaviour {

	private static ArmyDeploy instance;
	
	public static ArmyDeploy Instance{
		get{
			return instance;
		}
	}	
	
	void Awake()
	{
		instance = this;
		isActive=true;
	}

	public Transform playerPosParent;
	public Transform pc1Pos;
	DeploySpotInfo [] pcPos;

	public Transform npcPosParent;
	public Transform npc1Pos;
	DeploySpotInfo [] npcPos;

	public float gapBetweenChar = 2;

	public int nextDeployIndex;

	public int [] lineMax;
	public static int maxDeploy = 21;
	public static bool isDeploying;
	public static bool isActive;
	public static List<GameObject> deployedPawnList = new List<GameObject>();
	public static List<GameObject> deployedEnemyPawnList = new List<GameObject>();

	public static bool isDeployingEnemy;

	void Start()
	{


		if (UserData.Instance.userModel != null && UserData.Instance.userModel.HasFormation())
			return;

		SoundController.Create();

		if(GameData.Inst == null) {
			ResourceManager.Inst.PatchDataFile( ()=> {
				GameData.Init();
				CashData.Init();
				//TextData.Init();
				EventData.Init();
			});
		}

		//if(UserData.Instance.userModel==null)
		//	NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "kth18", string.Empty, ResponseLogin, null);

	}

	private void ResponseLogin(ResponseModel<UserModel> result)
	{
		if (result.ecode != 0)
			return;
		
		Debug.Log(result.data.account);
		UserData.Instance.userModel = result.data;
		Init();
	}

	void Init()
	{
		CalcDeployPosition();
		//UIDeployPanel.Instance.SetDeployPanel();
		//UIDeployPanel.Instance.AutoDeployNew();
	}

	public void CalcDeployPosition()
	{
		lineMax = new int[3];
		lineMax[0] = 8;
		lineMax[1] = 7;
		lineMax[2] = 6;

		pcPos = new DeploySpotInfo[maxDeploy];
		npcPos = new DeploySpotInfo[maxDeploy];

		int nIndex=0;
		for (int i = 0, j = 0; i < 3; i++)
		{
			for (int k = 0; k < 8 - i; k++, j++)
			{
				//Vector3 newPcPos = pc1Pos.localPosition;
				//Vector3 newNpcPos = npc1Pos.localPosition;
				int nLine = i;
				int nPos = i % lineMax[i];

				//GameObject playerPosGo = GameObject.Find(string.Format("21vs21/Player/{0}/{1:00}", i + 1, k + 1));
				//pc
				//pcPos[nIndex].trans = GameObject.Find(string.Format("21vs21/Player/{0}/{1:00}", i + 1, k + 1)).transform;
				//pcPos[i].pos = playerPosGo.transform.position;
				//pcPos[i].rot = playerPosGo.transform.rotation;	
				pcPos[nIndex].nLine=nLine;

				//playerPosGo = GameObject.Find(string.Format("21vs21/Enemy/{0}/{1:00}", i + 1, k + 1));
				//npc
				//npcPos[i].pos = playerPosGo.transform.position;
				//npcPos[i].rot = playerPosGo.transform.rotation;
				//npcPos[nIndex].trans = GameObject.Find(string.Format("21vs21/Enemy/{0}/{1:00}", i + 1, k + 1)).transform;
				npcPos[nIndex].nLine=nLine;
				nIndex++;
			}
		}
	}

	public GameObject Deploy(UICharToDeploy uiIcon)
	{
		if(nextDeployIndex>= pcPos.Length) {
			Debug.Log("over max. cannot Deploy");
			return null;
		}
		GameObject pawnGo = uiIcon.pawnGo;
		if(pawnGo==null || isDeployingEnemy)
			pawnGo = BattleResManager.CreateMassPawn(uiIcon.modelId);
			//pawnGo = BattleResManager.CreatePawnMassTest(uiIcon.charModel);
		pawnGo.name = uiIcon.memmodelNo.ToString();
		//pawnGo.name = uiIcon.charModel.ToString();
		pawnGo.SetActive(true);
		if(isDeployingEnemy) {
			pawnGo.transform.parent = null;
			//pawnGo.transform.position = npcPos[nextDeployIndex].trans.position;
			//pawnGo.transform.rotation = npcPos[nextDeployIndex].trans.rotation;
			deployedEnemyPawnList.Add(pawnGo);
		}
		else {
			//pawnGo.transform.parent = playerPosParent;
			pawnGo.transform.parent = null;
			//pawnGo.transform.position = pcPos[nextDeployIndex].trans.position;
			//pawnGo.transform.rotation = pcPos[nextDeployIndex].trans.rotation;
			//pawnGo.transform.parent = pcPos[nextDeployIndex].trans;
			//pawnGo.transform.localPosition = Vector3.zero;
			//pawnGo.transform.localRotation = Quaternion.identity;
			//pawnGo.transform.parent = null;
		}
		//pawnGo.transform.localRotation = Quaternion.identity;
		pcPos[nextDeployIndex].uiIcon = uiIcon;
		nextDeployIndex++;
		return pawnGo;
	}

	public void UnDeploy()
	{
		if(nextDeployIndex==0)
			return;
		nextDeployIndex--;
		pcPos[nextDeployIndex].uiIcon.UnDeploy();
		pcPos[nextDeployIndex].uiIcon=null;
	}

	public void UnDeployAll()
	{
		while(nextDeployIndex>0) {
			UnDeploy();
		}
	}

	public bool IsDeployed()
	{
		if(nextDeployIndex==0)
			return false;
		return true;
	}

	List<int> deployMemberNoList = new List<int>();

	public void SaveDeploy(int nSaveSlot)
	{
		deployMemberNoList.Clear ();
		for(int i=0; i<maxDeploy; i++) {
			if(pcPos[i].uiIcon==null)
				deployMemberNoList.Add(0);
			else
				deployMemberNoList.Add(pcPos[i].uiIcon.mNo);
		}

		if(deployMemberNoList.Count>0) {
			//serialize
			using (Stream stream = File.Open(GetDeployInfoFile(nSaveSlot), FileMode.Create))
			{
				var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
				bformatter.Serialize(stream, deployMemberNoList);
			}
		}
		else
			Debug.Log("Save fail  empty slot "+nSaveSlot);
	}

	public void LoadDeploy(int nSaveSlot)
	{
		if(isDeploying) return;
		isDeploying=true;
		StartCoroutine("CoLoadDeploy", nSaveSlot);
	}

	IEnumerator CoLoadDeploy(int nSaveSlot)
	{
		deployMemberNoList.Clear();
		//deserialize
		using (Stream stream = File.Open(GetDeployInfoFile(nSaveSlot), FileMode.Open))
		{
			var bformatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
			deployMemberNoList = (List<int>)bformatter.Deserialize(stream);
		}
		
		if(deployMemberNoList.Count>0) {
			UnDeployAll();
			for(int i=0; i<maxDeploy; i++) {
				if(deployMemberNoList[i]==0)
					continue;
				UICharToDeploy uiChar = UIDeployPanel.Instance.FindUIChar(deployMemberNoList[i]);
				uiChar.Deploy();
				yield return null;
			}
		}
		else
			Debug.Log("Load fail  empty slot "+nSaveSlot);
		isDeploying=false;
	}

	string GetDeployInfoFile(int nSaveSlot)
	{
		return string.Format("{0}/deploy{1}.bin",Application.persistentDataPath, nSaveSlot);
	}

	public void OnStart()
	{
		for(int i=0; i<maxDeploy; i++) {
			if(pcPos[i].uiIcon!=null)
				deployedPawnList.Add ( pcPos[i].uiIcon.pawnGo);
			else
				deployedPawnList.Add ( null);
		}
		nextDeployIndex=0;
		if (!MassiveBattle.Manager.BaseManager.Instance.IsRaid)
			UIDeployPanel.Instance.AutoDeployEnemy();
	}

}
